<template>
	<div class="index">
		<el-container class="h-h">
			<el-aside class="leftSlideDiv" width="240px" v-show="leftSildeStatus">
				<el-menu  text-color="#fff" style="min-height: 100%;" theme="dark" @select="goPage" :defaultActive="menu.ac" :defaultOpeneds="menu.open" >

					<div class="titleLogin">
						<img src="../assets/img/leftsilde.png" />
						<span class="yunname">云慧约</span>
					</div>
          <div v-if="showAdmin">
            <el-menu-item index="slideindex"><img src="../assets/img/index.png" />首页</el-menu-item>
            <el-menu-item index="business/businessindex"><img src="../assets/img/business.png" />业务类型</el-menu-item>
			<el-menu-item index="equipment/equipmentindex"><img src="../assets/img/equipment.png" />设备管理</el-menu-item>
            <el-menu-item index="windowss/windowssindex"><img src="../assets/img/window.png" />窗口管理</el-menu-item>
			<el-menu-item index="make" route="make"><img src="../assets/img/make.png" />预约规则</el-menu-item>
            <el-menu-item index="makeReservation/reservationindex"><img src="../assets/img/make-reservation.png" />预约记录</el-menu-item>
            <el-menu-item index="analysis"><img src="../assets/img/analysis.png" />统计分析</el-menu-item>
            <el-menu-item index="notes"><img src="../assets/img/notes.png" />预约须知</el-menu-item>
            <el-menu-item index="evaluate/evaluateindex"><img src="../assets/img/evaluate.png" />用户评价</el-menu-item>
          </div>
          <div v-else>
						<el-menu-item index="mechanismindex" class="slide-item"><img src="../assets/img/home.png" /> 首 页</el-menu-item>
						<el-submenu index="orgBusiness">
							<template slot="title">
								<img src="../assets/img/system.png" style="margin-right:8px;"/>
								<span>系统管理</span>
							</template>
							<el-menu-item-group>
								<el-menu-item index="orgBusiness/orgBusinessIndex"><img src="../assets/img/business.png" />业务类型</el-menu-item>
								<el-menu-item index="orgMake"><img src="../assets/img/make.png" />预约规则</el-menu-item>
								<el-menu-item index="orgNotes"><img src="../assets/img/notes.png" />预约须知</el-menu-item>
							</el-menu-item-group>
						</el-submenu>
            <el-menu-item index="orgPeople/orgPeopleIndex" class="slide-item"><img src="../assets/img/people.png" />人员管理</el-menu-item>
						<el-menu-item index="orgWebsite/orgWebsiteIndex" class="slide-item"><img src="../assets/img/website.png" />网点管理</el-menu-item>	
						<el-menu-item index="orgAnalysis" class="slide-item"><img src="../assets/img/analysis.png" />统计分析</el-menu-item>
						<el-menu-item index="orgEvaluate/orgEvaluateIndex" class="slide-item"><img src="../assets/img/evaluate.png" />用户评价</el-menu-item>
          </div>
				</el-menu>
			</el-aside>
			<el-container class="s-box">
				<el-header>
					<img class="toggleIcon" @click="toggleLeftSilde" src="../assets/img/toggle.png" />
					<div style="display: flex;align-items: center;height: 100%;justify-content: flex-end;flex: 1;">
						<el-select v-model="websiteValue" placeholder="请选择" v-show="showAdmin" style="width:300px;margin-right: 20px;" @change="changeWebsite($event)">
							<el-option
								v-for="(item,index) in website"
								:key="index"
								:label="item.latticeName"
								:value="item.id">
							</el-option>
						</el-select>
						<el-dropdown class="dropdwon" trigger="click" @command="handleCommand" menu-align='start' height="100%">
							<span class="el-dropdown-link" style="cursor: pointer;display: flex;align-items: center;">
								<img src="../assets/2.jpg" class="avator">
								<p v-if="showAdmin" class="name">网点管理员</p>
								<p v-else class="name">机构管理员</p>
							</span>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="gerenziliao">个人资料</el-dropdown-item>
								<el-dropdown-item command="pass">密码修改</el-dropdown-item>
								<el-dropdown-item command="email">邮箱修改</el-dropdown-item>
								<el-dropdown-item command="singout">退出</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</div>
					
				</el-header>
				<!--弹出层-->
				<el-dialog class="people" title="个人资料" :visible.sync="people" width="30%" center>
					<div class="people1">
						<span>姓名：</span>
						<p>{{user.name}}</p>
					</div>
					<div class="people1">
						<span>账号：</span>
						<p>{{user.logincode}}</p>
					</div>
					<div class="people1">
						<span>角色：</span>
						<p>{{user.rolecode}}</p>
					</div>
					<div class="people1">
						<span>绑定邮箱：</span>
						<p>{{user.mail}}</p>
					</div>
					<div class="people1">
						<span>服务电话：</span>
						<p>
							<span class="telphone" v-for="(item,index) in user.latticePointTel" :key="index">{{item}}</span>
						</p>
					</div>
					<div slot="footer" class="dialog-footer">
						<el-button type="primary" @click="innerVisible = true"><i class="el-icon-edit-outline"></i> 信息设置</el-button>
					</div>
					<el-dialog
						width="30%"
						title=""
						:visible.sync="innerVisible"
						append-to-body
						center>
						<el-form :model="userForm" label-width="80px">
							<el-form-item label="姓名:" >
								<el-input v-model="userForm.userName" autocomplete="off"></el-input>
							</el-form-item>
							<el-form-item label="账号:">
								<p>{{userForm.account}}</p>
							</el-form-item>
							<el-form-item label="角色:" >
								<p>{{userForm.role}}</p>
							</el-form-item>
							<el-form-item label="绑定邮箱:" >
								<el-input placeholder="请输入内容" v-model="userForm.email" :disabled="true">
									<el-button slot="append" @click="openEditEmail"><i class="el-icon-edit"></i>  修改</el-button>
								</el-input>
							</el-form-item>
							<el-form-item label="服务电话:">
								<el-input v-model="userForm.telPhone" autocomplete="off"></el-input>
							</el-form-item>
						</el-form>
						<div slot="footer" class="dialog-footer">
							<el-button style="padding: 12px 40px;" type="primary" @click="editUser">确 定</el-button>
						</div>
					</el-dialog>
			
				</el-dialog>
				<el-dialog class="passwords" top="0" title="密码修改" :visible.sync="passwords" width="30%" center>
					 <el-form :model="passWordForm" ref="passWordForm" :rules="rules" label-width="120px">
						<el-form-item label="原密码" prop="oldPassWord">
							<el-input type="password" v-model="passWordForm.oldPassWord" autocomplete="off"  minlength="6" maxlength="18"></el-input>
						</el-form-item>
						<el-form-item label="新密码" prop="newPassWord">
							<el-input type="password" v-model.trim="passWordForm.newPassWord" autocomplete="off" minlength="6" maxlength="18"></el-input>
						</el-form-item>
						<el-form-item label="再次输入密码" prop="newPassWordAlign">
							<el-input type="password" v-model.trim="passWordForm.newPassWordAlign" autocomplete="off" minlength="6" maxlength="18"></el-input>
						</el-form-item>
						<el-form-item style="text-align: center;">
							<el-button style="padding: 12px 40px;margin-left: -120px;" type="primary" @click="editPassWord('passWordForm')">提交</el-button>
						</el-form-item>
					</el-form>
				</el-dialog>
				<el-dialog class="email" title="邮箱修改" :visible.sync="email" width="30%" center @close="closeDialog">
					<el-form :model="emailForm" ref="emailForm" label-width="120px">
						<el-form-item
							prop="email"
							label="需要绑定的邮箱"
						>
							<el-input v-model="emailForm.newEmail">
								<el-button slot="append" :disabled="yzmStatus" @click="getCode">{{yzmText}}</el-button>
							</el-input>
						</el-form-item>
						<el-form-item
							prop="code"
							label="验证码"
							>
							<el-input v-model="emailForm.code"></el-input>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button style="padding: 12px 40px;" type="primary" @click="onSubmit">确认</el-button>
					</div>
				</el-dialog>
				<el-main>
					<!--<keep-alive>
						<router-view v-if="$route.meta.keepAlive"></router-view>
					</keep-alive>
					<router-view v-if="!$route.meta.keepAlive"></router-view>-->
					<router-view></router-view>
				</el-main>
			</el-container>
		</el-container>
	</div>
</template>
<script>
var timer= null
import {getLattice,getUserInfo,editUserInfo,editPassWord,getEmailCode,updateMail,setLattice,makeSearch} from '../api/getData.js'
import { inject } from 'async';
	export default {
		inject:['reload'],
		name: 'index',
		data: function() {
			var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.passWordForm.newPassWord) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
			return {
				menu: {
					ac: 'info',
					open: ['1', '2']
				},
				leftSildeStatus: true,
				people: false,
				passwords: false,
				email: false,
				website: [],
				websiteValue:'',
				user:{},
				innerVisible: false,
				userForm:{
					userName:'',
					telPhone:'',
					account:'',
					role:'',
					email:''
				},
				passWordForm:{
					oldPassWord:'',
					newPassWord:'',
					newPassWordAlign:''
				},
				rules:{
					oldPassWord:[
						{ required: true,message: '原密码不能为空',trigger: 'blur' }
					],
					newPassWord:[
						{ required: true,message: '密码不能为空',trigger: 'blur' },
						{ min: 6, max: 18,message: '密码为 6 到 18 位',trigger: ['blur','change']}
					],
					newPassWordAlign: [
						{ validator: validatePass, trigger: ['blur','change'] },
						{ required: true }
					]
				},
				emailForm:{
					newEmail:'',
					code:''
				},
				yzmStatus:false,
				yzmText:'获取验证码',
				yzmToken:"",
				isFirst:false,
				isMakeFirst:false,
				webList:[]
			}
		},
    computed:{
      showAdmin() {
        return window.sessionStorage.getItem("adminStatus") === "admin2"?true:false
      }
    },
		created() {
			console.log(window.sessionStorage.getItem("adminStatus"))
			this.getParams()
			this.getUser()
			console.log(this.websiteValue,"网点ID")
		}, // 创建时
		beforeMount: function() {}, // 挂载之前
		mounted: function() {
			this.menu.ac = this.defaultActive()
			// 当返回状态是admin2（网点管理员权限时再调网点列表接口），返回状态admin1是机构管理员权限，不调取
			if(window.sessionStorage.getItem("adminStatus") == 'admin2'){
				getLattice({}).then((res) =>{
					console.log(res.data,"获取网点",res.data.data[0].latticeName)
					if(res.data.code == 0){
						this.website = res.data.data;
						for(let i=0;i<res.data.data.length;i++){
							this.webList.push( res.data.data[i].id) 
						}
						this.websiteValue = JSON.parse(window.sessionStorage.getItem('latticeid'))

					}
				})
			}
		}, // 挂载之后
		beforeUpdate: function() {
			this.menu.ac = this.defaultActive()
		}, // 数据更新时调用,在渲染之前
		updated: function() {}, // 数据更新后,渲染后调用(禁止)
		beforeDestroy: function() {}, // 实例销毁前调用,解绑中间层的数据传输
		destroyed: function() {}, // 实例销毁后调用
		methods: {
			getParams(){
				this.isFirst = this.$route.query.isFirst 
			},
			// 获取网点下拉框数据
			getLattice(){
				getLattice({}).then((res) =>{
					if(res.data.code == 0){
						this.website = res.data.data
						for(let i=0;i<res.data.data.length;i++){
							this.webList.push( res.data.data[i].id) 
						}
					}
				}).catch((error)=>{
					console.log(error)
				})
			},
			// 切换网点
			changeWebsite(e){
				/* window.sessionStorage.setItem('latticeid', this.websiteValue)
				var lat  = JSON.parse(window.sessionStorage.getItem('latticeid')) */ 
				var lat = this.websiteValue
				// console.log(lat,"22222")
				setLattice({
					latticeid:lat
				}).then((res) =>{
					if(res.data.code === 0){
						window.sessionStorage.setItem('websiteValue',this.websiteValue)
						window.sessionStorage.setItem('latticeid', this.websiteValue)
						this.reload()
						 this.$router.push('/slideindex')
					}
				}).catch((error) =>{
					console.log(error)
				})
			},
			defaultActive() {
				return this.$route.path.replace('/', '')
			},
			goPage(i, t) {
				this.$router.push('/' + i)
			},
			/*个人信息*/
			handleCommand(command) {
				if(command === 'gerenziliao') {
					this.people = true
				} else if(command === 'pass') {
					this.passwords = true
				} else if(command === 'email') {
					this.email = true
				} else if(command === 'singout') {
					this.$message({
						type: 'success',
						message: '退出成功'
					})
					this.$router.push('/')
				}
			},
			/*toggle切换左侧*/
			toggleLeftSilde() {
				var $leftSlide = document.querySelector(".leftSlideDiv")
				$leftSlide.classList.toggle("leftSlide")
			},
			// 获取个人资料
			getUser(){
				getUserInfo({}).then((res) =>{
					console.log(res.data,"个人资料")
					if(res.data.code == 0){
						this.user = res.data.data
						this.userForm.userName = res.data.data.name
						this.userForm.account = res.data.data.logincode
						this.userForm.role = res.data.data.rolecode
						this.userForm.email = res.data.data.mail
						// res.data.data.latticePointTel = res.data.data.latticePointTel.join(",")
						this.userForm.telPhone = res.data.data.latticePointTel
					}else{
						this.user = []
					}
				}).catch((error) =>{
					console.log(error)
				})
			},
			// 修改个人资料
			editUser(){
				editUserInfo({
					latticePointTel:this.userForm.telPhone,
					name:this.userForm.userName
				}).then((res) =>{
					console.log(res.data)
					if(res.data.code === 0){
						this.$message({
							message: res.data.msg,
							type: 'success'
						});
						this.innerVisible = false
						this.getUser()
					}else{
						this.$message.error(res.data.msg)
					}
				}).catch((error) =>{
					console.log(error)
				})
			},
			// 修改密码
			editPassWord(formName){
				this.$refs[formName].validate((valid) => {
          if (valid) {
						editPassWord({
							oldPassword:this.passWordForm.oldPassWord,
							password:this.passWordForm.newPassWord
						}).then((res) =>{
							console.log(res.data)
							if(res.data.code == 0){
								this.$message({
									message: res.data.msg + ',请重新登录！',
									type: 'success'
								});
								this.passwords = false
								setTimeout(()=>{
									this.$router.push('/')
								},1000)
							}else{
								this.$message({
									message: res.data.msg,
									type: 'error'
								});
							}
						}).catch((error) =>{
							console.log(error)
						})
          } else {
            console.log('error submit!!');
            return false;
          }
        })
			},
			//获取邮箱验证码
			getCode(){
				let reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
				if(!reg.test(this.emailForm.newEmail)) {
				 	this.$message.error("邮箱格式不正确")
				}else{
					getEmailCode({
					 	toAddress:this.emailForm.newEmail
					}).then((res) =>{
					 	console.log(res.data,"发送邮箱验证码")
					 	if(res.data.code == 0){
					 		this.$message({
					 			message:res.data.msg,
					 			type: 'success'
					 		})
					 		this.yzmToken = res.data.data.token
					 	}
					}).catch((error) =>{
						 console.log(error)
					})
					var s = 60
					clearInterval(timer)
					timer = setInterval(()=>{
						this.yzmStatus = true
						s--
						this.yzmText = s + 's'
						if(s === 0){
							this.yzmStatus = false
							this.yzmText = '获取验证码'
							s = 0
							clearInterval(timer)
						}
					},1000)
				}
			},
			onSubmit(){
				updateMail({
					code:this.emailForm.code,
					mail:this.emailForm.newEmail,
					token:this.yzmToken
				}).then((res) =>{
					console.log(res.data)
					if(res.data.code === 0){
						this.$message({
							message:"邮箱更改成功",
							type:"success"
						})
						this.email = false
						this.getUser()
						
					}else if(res.data.code === 1){
						this.$message.error("邮箱绑定失败")
					}
				}).catch((error) =>{
					console.log(error)
				})
			},
			openEditEmail(){
				this.innerVisible = false
				this.people = false
				this.email = true
			},
			closeDialog(){
				clearInterval(timer)
				this.yzmStatus = false
				this.yzmText = '获取验证码'
				this.emailForm.newEmail = ''
				this.emailForm.code = ''
			}
		} // 函数
	}
</script>
<style lang='scss'>
	html,
	body {
		font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
	}

	.avator {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		cursor: pointer;
	}

	.s-box {
		min-width: 960px;
		width: 100%;
		height: 100%;
		overflow: hidden;
	}
	.index {
		height: 100%;
		box-sizing: border-box;
		min-width: 1200px;
		.h-h {
			height: 100%;
			box-sizing: border-box;
			.titleLogin {
				height: 64px;
				padding-left: 24px;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				background-color: #0A1021;
			}
			.el-menu {
				background-color: #222A43;
			}
			.yunname {
				font-family: HYk1gj;
				font-size: 20px;
				color: #FFFFFF;
				font-weight: bold;
				margin-left: 8px;
			}
		}
	}

	.el-menu {
		background-color: #324057;
		text-align: left;
		.el-menu-item:focus,
		.el-menu-item:hover,
		.el-submenu__title:hover {
			background-color: #0A1021;
			border-left: 2px solid #FFC535;
		}
		.el-menu-item.is-active {
			color: #fff;
			background-color: #0A1021;
			border-left: 2px solid #FFC535;
		}
		.el-menu-item {
			border-left: 2px solid #324057;
			display: flex;
			align-items: center;
			height: 40px;
			line-height: 40px;
			img {
				margin-left: 22px;
				margin-right: 12px;
			}
		}
		.slide-item{
			height: 50px;
			line-height: 50px;
		}
		.el-submenu__title{
			border-left: 2px solid #324057;
			height: 50px;
			line-height: 50px;
			img{
				margin-left: 22px;
				margin-right: 10px;
			}
		}
		.el-menu-item-group__title{
			padding: 0!important;
		}
	}

	.leftSlide {
		display: none;
	}

	.people {
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		.people1 {
			box-sizing: border-box;
			margin: 10px 0;
			width: 100%;
			display: flex;
			justify-content: space-between;
			padding: 10px 30px;
			font-size: 16px;
		}
	}

	.passwords,
	.email {
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		align-items: center;
		.passwordsInner,
		.emailInner {
			padding: 0 100px;
			margin: 30px 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			span {
				width: 40%;
				font-size: 16px;
			}
			.emailYzmDig {
				width: 50%;
			}
		}
		.passwordsInnerBtn,
		.emailBtn {
			display: flex;
			justify-content: center;
			.el-button {
				width: 20%;
			}
		}
	}

	.el-header,
	.el-footer {
		background-color: #fff;
		padding: 0 40px;
		color: #333;
		text-align: center;
		height: 64px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: #ccc 1px 1px 10px;
		z-index: 9;
		.toggleIcon {
			cursor: pointer;
		}
		.dropdwon {
			height: 100%;
			background: rgba(0, 0, 0, 0.04);
			box-sizing: border-box;
			padding-top: 7px;
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding: 0 20px;
			
		}
		.name {
			font-size: 14px;
			color: #333437;
			margin-left: 5px;
		}
	}

	.el-aside {
		background-color: rgb(50, 64, 87);
		color: #333;
		text-align: center;
	}

	.el-main {
		height: calc(100% - 60px);
		overflow-y: scroll;
		background-color: #E9EEF3;
		color: #333;
		padding:20px 30px;
   		min-width: 960px;

	}
</style>
